package com.common.util;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.log4j.Logger;


/**
 * Created by robin on 2016/9/2.
 * 阿里大于短信服务
 */
public class ALiDaYuSms {

    protected Logger log =  Logger.getLogger(ALiDaYuSms.class);

    /**
     * 发送短信
     * @param phoneNum 电话号码
     * @param content  内容
     * @param tempCode 模板编号
     * @return         结果
     * @throws ApiException
     */
    public boolean send(String phoneNum,String content,String tempCode) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(this.getUrl(), this.getAppKey(),this.getAppSecret());
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType( "normal" );
        req.setSmsFreeSignName(this.getSignName());
        req.setRecNum(phoneNum);
        req.setSmsParamString(content);
        req.setSmsTemplateCode(tempCode);
        AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
        String result = rsp.getBody();
        if(!result.contains("alibaba_aliqin_fc_sms_num_send_response")){
            log.fatal(result);
            throw new RuntimeException("短信发送发生未知异常，请联系管理员");
        }else{
            if(result.contains("false")) return false;
        }
        return true;
    }

    /**
     * 获取地址
     * @return 结果
     */
    public String getUrl(){
        return this.getALiDaYu("alidayu.url","https://eco.taobao.com/router/rest");
    }

    /**
     * 获取app key
     * @return 结果
     */
    public String getAppKey(){
        return this.getALiDaYu("alidayu.app.key","23446882");
    }

    /**
     * 获取app 秘钥
     * @return 结果
     */
    public String getAppSecret(){
        return this.getALiDaYu("alidayu.app.secret","fdca0e0a474660c914094be41c957013");
    }

    /**
     * 获取发送短信签名
     * @return 结果
     */
    public String getSignName(){
        return this.getALiDaYu("alidayu.sign.name","慧知云");
    }

    /**
     * 获取配置文件中的阿里大于短信服务必要的配置
     * @param key          配置文件中的键名
     * @param defaultValue 默认值
     * @return             结果
     */
    private String getALiDaYu(String key,String defaultValue){
        return defaultValue;
    }
}
